/**
 * 消息派发
 * by wyy
 */
class Message extends Singleton {
    protected _listener = {};

    constructor() {
        super();
    }

    dispatch($type, ...param: any[]) {
        let listener: Array<any> = this._listener[$type];
        if (listener) {
            for (let l of listener) {
                l["func"].apply(l["obj"], param);
            }
        }
    }

    addListener($type, $func: Function, $obj) {
        (!this._listener[$type]) && (this._listener[$type] = new Array());
        this._listener[$type].push({ "obj": $obj, "func": $func });
    }
    removeListener($type, $func: Function, $obj) {
        let listener: Array<any> = this._listener[$type];
        if (listener) {
            for (let i in listener) {
                if ((listener[i]["obj"] == $obj) && (listener[i]["func"] == $func)) {
                    listener.splice(Number(i), 1);
                }
            }
        }
    }
    /**
     * 根据类型删除监听
     * @param $type 类型
     */
    removeListenerByType($type) {
        this._listener[$type] = null;
        delete this._listener[$type];
    }
    /**
     * 根据监听者删除监听
     * @param $obj 监听者
     */
    removeListenerByObj($obj) {
        let keys = Object.keys(this._listener);
        for (let i: number = 0, len = keys.length; i < len; i++) {
            let type = keys[i];
            let arr: Array<any> = this._listener[type];
            for (let j = 0; j < arr.length; j++) {
                if (arr[j]["obj"] == $obj) {
                    arr.splice(j, 1);
                    j--;
                }
            }
            if (arr.length == 0) {
                this._listener[type] = null;
                delete this._listener[type];
            }
        }
    }
}
